<template>
  <div class="advanced-markdown-renderer">
    <div
      v-for="(segment, index) in parsedSegments"
      :key="index"
      :class="['content-segment', `segment-${segment.type}`]"
    >
      <!-- 普通文本内容 -->
      <div
        v-if="segment.type === 'text'"
        class="text-content"
        v-html="segment.content"
      ></div>

      <!-- ECharts图表 -->
      <div
        v-if="segment.type === 'echarts'"
        class="chart-container"
      >
        <div class="chart-header">
          <div class="chart-title">
            <el-icon><TrendCharts /></el-icon>
            <span>{{ segment.title || '数据图表' }}</span>
          </div>
          <div class="chart-actions">
            <el-button
              type="text"
              size="small"
              @click="viewChartData(segment)"
              title="查看数据"
            >
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="downloadChart(segment, index)"
              title="下载图表"
            >
              <el-icon><Download /></el-icon>
            </el-button>
          </div>
        </div>
        <div
          :ref="el => setChartRef(el, index)"
          :id="`chart-${componentId}-${index}`"
          class="chart-element"
          @click="handleChartClick(segment, $event)"
        ></div>
        <div v-if="segment.error" class="chart-error">
          <el-alert
            :title="segment.error"
            type="error"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="error-details">
                <p>图表渲染失败，请检查数据格式</p>
                <el-button
                  type="text"
                  size="small"
                  @click="showChartConfig(segment)"
                >
                  查看配置
                </el-button>
              </div>
            </template>
          </el-alert>
        </div>
      </div>

      <!-- 增强代码块 -->
      <div
        v-if="segment.type === 'code'"
        class="enhanced-code-container"
      >
        <div class="code-header">
          <div class="code-language">
            <el-icon><Document /></el-icon>
            <span>{{ segment.language || 'Code' }}</span>
          </div>
          <div class="code-actions">
            <el-button
              type="text"
              size="small"
              @click="copyCode(segment)"
              title="复制代码"
            >
              <el-icon><CopyDocument /></el-icon>
            </el-button>
          </div>
        </div>
        <div
          class="code-content"
          v-html="segment.content"
        ></div>
      </div>
    </div>

    <!-- 配置查看对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      title="图表配置"
      width="60%"
      :modal="true"
    >
      <el-input
        v-model="currentConfigText"
        type="textarea"
        :rows="15"
        readonly
        class="config-viewer"
      />
      <template #footer>
        <el-button @click="showConfigDialog = false">关闭</el-button>
        <el-button type="primary" @click="copyConfig">复制配置</el-button>
      </template>
    </el-dialog>

    <!-- 数据查看对话框 -->
    <el-dialog
      v-model="showDataDialog"
      title="图表数据"
      width="80%"
      :modal="true"
      class="data-dialog"
    >
      <div class="data-viewer-container">
        <div class="data-header">
          <div class="data-info">
            <span class="data-title">{{ currentDataInfo.title }}</span>
            <span class="data-count">共 {{ currentDataInfo.totalRows }} 条数据</span>
          </div>
          <div class="data-actions">
            <el-button
              size="small"
              @click="exportDataAsCSV"
              type="success"
              plain
            >
              <el-icon><Download /></el-icon>
              导出CSV
            </el-button>
          </div>
        </div>

        <!-- 数据表格 -->
        <div class="data-table-container">
          <el-table
            :data="currentDataInfo.tableData"
            stripe
            border
            height="400"
            :show-overflow-tooltip="true"
            class="data-table"
          >
            <el-table-column
              v-for="column in currentDataInfo.columns"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :sortable="column.sortable"
            >
              <template #default="scope">
                <span v-if="column.type === 'number'" class="number-cell">
                  {{ formatNumber(scope.row[column.prop]) }}
                </span>
                <span v-else>{{ scope.row[column.prop] }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="showDataDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import {
  TrendCharts,
  Download,
  Document,
  CopyDocument,
  DocumentCopy
} from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import * as echarts from 'echarts'

// Props
const props = defineProps({
  content: {
    type: String,
    required: true,
    default: ''
  },
  isDarkMode: {
    type: Boolean,
    default: false
  }
})

// 组件状态
const componentId = ref(`renderer-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`)
const parsedSegments = ref([])
const chartRefs = ref(new Map())
const chartInstances = ref(new Map())
const showConfigDialog = ref(false)
const currentConfigText = ref('')

// 🎯 新增：数据查看功能状态
const showDataDialog = ref(false)
const currentDataInfo = ref({
  title: '',
  columns: [],
  tableData: [],
  totalRows: 0
})

// 配置MarkdownIt
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (error) {
        console.warn('代码高亮失败:', error)
      }
    }
    return ''
  }
})

// 设置图表ref
const setChartRef = (el, index) => {
  if (el) {
    chartRefs.value.set(index, el)
  }
}

// 智能JSON对象匹配器 - 解决截断问题
const findCompleteJSONObjects = (text) => {
  const matches = []
  let pos = 0

  while (pos < text.length) {
    // 寻找JSON对象的开始位置
    const openBrace = text.indexOf('{', pos)
    if (openBrace === -1) break

    // 检查前面是否有换行或空白（确保是独立的JSON）
    const beforeChar = openBrace > 0 ? text[openBrace - 1] : '\n'
    if (beforeChar !== '\n' && beforeChar !== ' ' && beforeChar !== '\t' && openBrace !== 0) {
      pos = openBrace + 1
      continue
    }

    // 匹配完整的JSON对象（处理嵌套大括号）
    let braceCount = 0
    let inString = false
    let escaped = false
    let endPos = openBrace

    for (let i = openBrace; i < text.length; i++) {
      const char = text[i]

      if (escaped) {
        escaped = false
        continue
      }

      if (char === '\\' && inString) {
        escaped = true
        continue
      }

      if (char === '"') {
        inString = !inString
        continue
      }

      if (!inString) {
        if (char === '{') {
          braceCount++
        } else if (char === '}') {
          braceCount--
          if (braceCount === 0) {
            endPos = i + 1
            break
          }
        }
      }
    }

    if (braceCount === 0) {
      const jsonText = text.slice(openBrace, endPos)

      // 验证是否包含ECharts相关字段
      if (/["'](?:series|xAxis|yAxis|data|title|option)["']/.test(jsonText)) {
        matches.push({
          start: openBrace,
          end: endPos,
          content: jsonText
        })
      }
    }

    pos = endPos > openBrace ? endPos : openBrace + 1
  }

  return matches
}

// 解析内容为不同的段落类型
const parseContent = (content) => {
  if (!content || typeof content !== 'string') {
    return [{ type: 'text', content: '' }]
  }

  const segments = []
  let currentPos = 0

  // 1. 首先匹配代码块中的JSON
  const codeBlockRegex = /```(?:json|echarts|chart)?\s*\n?([\s\S]*?)\n?```/gi
  const codeMatches = []
  let match

  while ((match = codeBlockRegex.exec(content)) !== null) {
    codeMatches.push({
      type: 'echarts',
      start: match.index,
      end: match.index + match[0].length,
      content: match[1].trim(),
      parser: parseEChartsConfig,
      match: match
    })
  }

  // 2. 然后匹配独立的JSON对象（避免与代码块重叠）
  const jsonMatches = findCompleteJSONObjects(content)

  jsonMatches.forEach(jsonMatch => {
    // 检查是否与代码块重叠
    const overlapsWithCodeBlock = codeMatches.some(codeMatch =>
      jsonMatch.start >= codeMatch.start && jsonMatch.end <= codeMatch.end
    )

    if (!overlapsWithCodeBlock) {
      codeMatches.push({
        type: 'echarts',
        start: jsonMatch.start,
        end: jsonMatch.end,
        content: jsonMatch.content,
        parser: parseStandaloneJSON,
        match: [jsonMatch.content, jsonMatch.content] // 模拟match数组格式
      })
    }
  })

  // 3. 按位置排序所有匹配
  codeMatches.sort((a, b) => a.start - b.start)

  // 4. 构建段落
  codeMatches.forEach(matchItem => {
    // 添加前面的文本
    if (matchItem.start > currentPos) {
      const textContent = content.slice(currentPos, matchItem.start).trim()
      if (textContent) {
        segments.push({
          type: 'text',
          content: md.render(textContent)
        })
      }
    }

    // 添加特殊内容段落
    try {
      const parsed = matchItem.parser(matchItem.match)
      if (parsed) {
        segments.push({
          type: matchItem.type,
          ...parsed
        })
      }
    } catch (error) {
      console.error(`解析${matchItem.type}内容失败:`, error)
      // 解析失败时作为普通文本处理
      segments.push({
        type: 'text',
        content: md.render(matchItem.content)
      })
    }

    currentPos = matchItem.end
  })

  // 5. 添加剩余文本
  if (currentPos < content.length) {
    const remainingText = content.slice(currentPos).trim()
    if (remainingText) {
      segments.push({
        type: 'text',
        content: md.render(remainingText)
      })
    }
  }

  // 6. 如果没有找到任何特殊内容，就全部作为文本处理
  if (segments.length === 0) {
    segments.push({
      type: 'text',
      content: md.render(content)
    })
  }

  return segments
}

// 解析代码块中的ECharts配置
const parseEChartsConfig = (match) => {
  let configText = match[1].trim()
  return parseJSONConfig(configText)
}

// 解析独立的JSON配置
const parseStandaloneJSON = (match) => {
  let configText = match[1].trim()
  return parseJSONConfig(configText)
}

// 通用JSON配置解析
const parseJSONConfig = (configText) => {
  try {
    let config

    // 尝试直接解析JSON
    if (configText.startsWith('{') || configText.startsWith('[')) {
      config = JSON.parse(configText)
    } else {
      // 尝试提取JSON部分
      const jsonMatch = configText.match(/\{[\s\S]*\}/)
      if (jsonMatch) {
        config = JSON.parse(jsonMatch[0])
      } else {
        throw new Error('未找到有效的JSON配置')
      }
    }

    // 验证是否是有效的ECharts配置
    if (!isValidEChartsConfig(config)) {
      throw new Error('无效的ECharts配置格式')
    }

    return {
      config: config,
      originalText: configText,
      title: extractChartTitle(config)
    }
  } catch (error) {
    // 解析失败：尝试白名单函数预处理 -> 解析 -> 函数还原
    try {
      const { text: preprocessedText, placeholders } = preprocessWhitelistFunctions(configText)

      // 预处理后再解析
      let config
      if (preprocessedText.startsWith('{') || preprocessedText.startsWith('[')) {
        config = JSON.parse(preprocessedText)
      } else {
        const jsonMatch = preprocessedText.match(/\{[\s\S]*\}/)
        if (jsonMatch) {
          config = JSON.parse(jsonMatch[0])
        } else {
          throw new Error('预处理后仍未找到有效的JSON配置')
        }
      }

      // 还原白名单函数
      restoreWhitelistFunctions(config, placeholders)

      if (!isValidEChartsConfig(config)) {
        throw new Error('无效的ECharts配置格式')
      }

      return {
        config: config,
        originalText: configText,
        title: extractChartTitle(config)
      }
    } catch (fallbackErr) {
      console.warn('图表配置解析失败:', error.message || error)
      console.warn('白名单预处理后解析失败:', fallbackErr.message || fallbackErr)
      return null
    }
  }
}

// 白名单函数键路径：仅允许以下键出现函数
const WHITELIST_FUNCTION_KEYS = [
  'formatter',
  'color'
]

// 安全关键字黑名单，防止执行有风险的代码
const FORBIDDEN_TOKENS = [
  'window', 'document', 'globalThis', 'self', 'global', 'Function', 'eval', 'import(', 'export',
  'XMLHttpRequest', 'fetch', 'WebSocket', 'localStorage', 'sessionStorage', 'IndexedDB', 'caches',
  'new ', 'class ', 'async ', 'await ', 'navigator', 'location', 'top', 'parent'
]

// 预处理：将白名单键上的 function(...) { ... } 替换为占位符，便于 JSON.parse
const preprocessWhitelistFunctions = (rawText) => {
  let text = String(rawText)
  const placeholders = new Map()
  let idx = 0

  // 针对常见键的函数值做替换
  WHITELIST_FUNCTION_KEYS.forEach((key) => {
    // eslint-disable-next-line no-useless-escape
    const regex = new RegExp(`("${key}"\\s*:\\s*)function\\s*\\(([^)]*)\\)\\s*\\{([\\s\\S]*?)\\}`,'g')
    text = text.replace(regex, (_m, prefix, args, body) => {
      const fnString = `function(${args}){${body}}`
      const id = `__FUNC_PLACEHOLDER_${key.toUpperCase()}_${idx++}__`
      placeholders.set(id, fnString)
      return `${prefix}"${id}"`
    })

    // 兼容未加引号的键名（宽松写法）：color: function(...) {...}
    const looseRegex = new RegExp(`(${key}\\s*:\\s*)function\\s*\\(([^)]*)\\)\\s*\\{([\\s\\S]*?)\\}`,'g')
    text = text.replace(looseRegex, (_m, prefix, args, body) => {
      const fnString = `function(${args}){${body}}`
      const id = `__FUNC_PLACEHOLDER_${key.toUpperCase()}_${idx++}__`
      placeholders.set(id, fnString)
      // 统一替换为带引号键名，便于 JSON.parse
      return `"${key}": "${id}"`
    })
  })

  return { text, placeholders }
}

// 还原：将占位符还原为函数对象（仅限白名单键）
const restoreWhitelistFunctions = (obj, placeholders) => {
  const restoreRecursively = (node) => {
    if (Array.isArray(node)) {
      node.forEach(restoreRecursively)
      return
    }
    if (node && typeof node === 'object') {
      Object.keys(node).forEach((k) => {
        const val = node[k]
        if (typeof val === 'string' && placeholders.has(val)) {
          const fnStr = placeholders.get(val)
          if (k && WHITELIST_FUNCTION_KEYS.includes(k) && isSafeFunctionString(fnStr)) {
            node[k] = buildFunctionFromString(fnStr)
          } else {
            // 非白名单键或不安全，退化为字符串
            node[k] = String(val)
          }
        } else if (val && typeof val === 'object') {
          restoreRecursively(val)
        }
      })
    }
  }
  restoreRecursively(obj)
}

// 安全校验：禁止出现高危标记；限制函数字符串长度
const isSafeFunctionString = (fnStr) => {
  if (typeof fnStr !== 'string') return false
  if (fnStr.length > 2000) return false
  const lower = fnStr.toLowerCase()
  return !FORBIDDEN_TOKENS.some((tok) => lower.includes(tok.toLowerCase()))
}

// 构造函数对象：使用 new Function 封装返回，避免直接 eval
const buildFunctionFromString = (fnStr) => {
  try {
    // 形如 function(params){ ... }
    const factory = new Function(`return (${fnStr});`)
    const fn = factory()
    if (typeof fn === 'function') return fn
    // 退化为原字符串
    return fnStr
  } catch (e) {
    console.warn('函数还原失败，已降级为字符串:', e)
    return fnStr
  }
}

// 验证ECharts配置
const isValidEChartsConfig = (config) => {
  if (!config || typeof config !== 'object') return false

  // 基本的ECharts配置验证 - 更宽松的条件
  const hasValidStructure =
    config.xAxis !== undefined ||
    config.yAxis !== undefined ||
    config.series !== undefined ||
    config.data !== undefined ||
    config.dataset !== undefined ||
    config.option !== undefined ||
    (config.title !== undefined && (config.series !== undefined || config.data !== undefined))

  return hasValidStructure
}

// 提取图表标题
const extractChartTitle = (config) => {
  if (config.title && config.title.text) {
    return config.title.text
  }
  if (config.series && config.series[0] && config.series[0].name) {
    return config.series[0].name
  }
  return '数据图表'
}

// 渲染图表
const renderChart = async (segment, index) => {
  if (!segment.config || segment.error) return

  await nextTick()

  const chartElement = chartRefs.value.get(index)
  if (!chartElement) {
    console.error('图表容器未找到:', index)
    return
  }

  try {
    // 销毁已存在的图表实例
    const existingChart = chartInstances.value.get(index)
    if (existingChart) {
      existingChart.dispose()
    }

    // 创建新的图表实例
    const chart = echarts.init(chartElement, props.isDarkMode ? 'dark' : 'light')

    // 设置图表配置
    const finalConfig = enhanceChartConfig(segment.config)
    chart.setOption(finalConfig, true)

    // 保存图表实例
    chartInstances.value.set(index, chart)

    // 设置响应式
    const resizeObserver = new ResizeObserver(() => {
      chart.resize()
    })
    resizeObserver.observe(chartElement)

    // 图表点击事件
    chart.on('click', (params) => {
      console.log('图表点击事件:', params)
    })

  } catch (error) {
    console.error('图表渲染失败:', error)
    segment.error = `渲染失败: ${error.message}`
  }
}

// 增强图表配置
const enhanceChartConfig = (config) => {
  const enhanced = deepClonePreservingFunctions(config)

  // 添加默认样式
  if (!enhanced.backgroundColor) {
    enhanced.backgroundColor = 'transparent'
  }

  // 添加默认动画
  if (!enhanced.animation) {
    enhanced.animation = true
    enhanced.animationDuration = 1000
  }

  // 添加数据缩放（如果有坐标轴）
  if (!enhanced.dataZoom && (enhanced.xAxis || enhanced.yAxis)) {
    enhanced.dataZoom = [
      {
        type: 'inside',
        xAxisIndex: 0
      }
    ]
  }

  // 添加提示框
  if (!enhanced.tooltip) {
    enhanced.tooltip = {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    }
  }

  // 添加图例
  if (!enhanced.legend && enhanced.series && enhanced.series.length > 1) {
    enhanced.legend = {
      top: 10
    }
  }

  // Fallback: 单系列柱状图且未使用函数着色时，按数据项分配颜色，避免整列同色
  try {
    if (Array.isArray(enhanced.series) && enhanced.series.length === 1) {
      const s = enhanced.series[0] || {}
      const isBar = s.type && String(s.type).toLowerCase().includes('bar')
      const hasFunctionColor = s.itemStyle && typeof s.itemStyle.color === 'function'
      const dataArr = Array.isArray(s.data) ? s.data : []
      if (isBar && !hasFunctionColor && dataArr.length > 0) {
        // 取调色板：优先使用 option.color，其次使用一组默认颜色
        const palette = Array.isArray(enhanced.color) && enhanced.color.length > 0
          ? enhanced.color
          : [
              '#c23531','#2f4554','#61a0a8','#d48265','#91c7ae',
              '#749f83','#ca8622','#bda29a','#6e7074','#546570'
            ]
        s.data = dataArr.map((item, idx) => {
          if (item && typeof item === 'object') {
            // 若已指定颜色则保持不变
            const hasItemColor = item.itemStyle && item.itemStyle.color
            if (hasItemColor) return item
            const color = palette[idx % palette.length]
            return { ...item, itemStyle: { ...(item.itemStyle || {}), color } }
          }
          const color = palette[idx % palette.length]
          return { value: item, itemStyle: { color } }
        })
      }
    }
  } catch (e) {
    console.warn('应用柱状图着色回退失败:', e)
  }

  return enhanced
}

// 深拷贝并保留函数
const deepClonePreservingFunctions = (value) => {
  if (value === null || typeof value !== 'object') return value
  if (typeof value === 'function') return value
  if (Array.isArray(value)) return value.map(deepClonePreservingFunctions)
  const cloned = {}
  for (const key in value) {
    const v = value[key]
    cloned[key] = typeof v === 'function' ? v : deepClonePreservingFunctions(v)
  }
  return cloned
}

// 🎯 新增：查看图表数据
const viewChartData = (segment) => {
  if (!segment.config) {
    ElMessage.warning('该图表没有配置数据，无法查看。')
    return
  }

  try {
    const extractedData = extractChartData(segment.config)

    if (!extractedData || extractedData.tableData.length === 0) {
      ElMessage.warning('该图表没有可显示的数据。')
      return
    }

    currentDataInfo.value = {
      title: segment.title || extractedData.title || '图表数据',
      columns: extractedData.columns,
      tableData: extractedData.tableData,
      totalRows: extractedData.tableData.length
    }

    showDataDialog.value = true
  } catch (error) {
    console.error('解析图表数据失败:', error)
    ElMessage.error('解析图表数据失败，请检查数据格式。')
  }
}

// 🎯 新增：提取图表数据的核心函数
const extractChartData = (config) => {
  const result = {
    title: config.title?.text || '图表数据',
    columns: [],
    tableData: []
  }

  // 处理dataset格式的数据
  if (config.dataset && config.dataset.source) {
    return extractDatasetData(config.dataset, result)
  }

  // 处理series数据
  if (config.series && Array.isArray(config.series)) {
    return extractSeriesData(config, result)
  }

  return result
}

// 🎯 新增：处理dataset格式数据
const extractDatasetData = (dataset, result) => {
  const source = dataset.source

  if (Array.isArray(source) && source.length > 0) {
    const firstRow = source[0]

    if (Array.isArray(firstRow)) {
      // 二维数组格式：[['产品', '销量'], ['A', 100], ['B', 200]]
      const headers = firstRow
      result.columns = headers.map((header, index) => ({
        prop: `col_${index}`,
        label: String(header),
        width: 120,
        sortable: true,
        type: typeof source[1]?.[index] === 'number' ? 'number' : 'string'
      }))

      result.tableData = source.slice(1).map(row => {
        const rowData = {}
        headers.forEach((header, index) => {
          rowData[`col_${index}`] = row[index]
        })
        return rowData
      })
    } else if (typeof firstRow === 'object') {
      // 对象数组格式：[{name: 'A', value: 100}, {name: 'B', value: 200}]
      const keys = Object.keys(firstRow)
      result.columns = keys.map(key => ({
        prop: key,
        label: key,
        width: 120,
        sortable: true,
        type: typeof firstRow[key] === 'number' ? 'number' : 'string'
      }))

      result.tableData = source
    }
  }

  return result
}

// 🎯 新增：处理series格式数据
const extractSeriesData = (config, result) => {
  const allData = []
  const xAxisData = config.xAxis?.data || []

  config.series.forEach((series) => {
    if (!series.data) return

    series.data.forEach((dataItem, dataIndex) => {
      const rowData = {}

      // 添加X轴标签（如果有）
      if (xAxisData.length > dataIndex) {
        rowData.category = xAxisData[dataIndex]
      } else {
        rowData.category = `项目${dataIndex + 1}`
      }

      // 处理不同类型的数据项
      if (typeof dataItem === 'object' && dataItem !== null) {
        // 对象格式：{value: 100, name: 'A'} 或 {value: [10, 20], name: 'A'}
        if (dataItem.name) {
          rowData.name = dataItem.name
        }

        if (Array.isArray(dataItem.value)) {
          dataItem.value.forEach((val, valIndex) => {
            rowData[`value_${valIndex}`] = val
          })
        } else {
          rowData.value = dataItem.value
        }

        // 复制其他属性
        Object.keys(dataItem).forEach(key => {
          if (key !== 'value' && key !== 'name') {
            rowData[key] = dataItem[key]
          }
        })
      } else {
        // 简单数值
        rowData.value = dataItem
      }

      // 添加系列名称
      if (series.name) {
        rowData.series = series.name
      }

      allData.push(rowData)
    })
  })

  if (allData.length > 0) {
    // 根据数据结构生成列定义
    const sampleData = allData[0]
    result.columns = Object.keys(sampleData).map(key => ({
      prop: key,
      label: getColumnLabel(key),
      width: key === 'name' || key === 'category' ? 150 : 120,
      sortable: true,
      type: typeof sampleData[key] === 'number' ? 'number' : 'string'
    }))

    result.tableData = allData
  }

  return result
}

// 🎯 新增：获取列标签的友好名称
const getColumnLabel = (key) => {
  const labelMap = {
    'category': '类别',
    'name': '名称',
    'value': '数值',
    'series': '系列',
    'x': 'X轴',
    'y': 'Y轴'
  }

  return labelMap[key] || key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}

// 🎯 新增：导出图表数据为CSV
const exportDataAsCSV = () => {
  const data = currentDataInfo.value.tableData
  const columns = currentDataInfo.value.columns

  if (data.length === 0) {
    ElMessage.warning('没有数据可导出。')
    return
  }

  const header = columns.map(col => col.label).join(',') + '\n'
  const csvContent = header + data.map(row => {
    return columns.map(col => {
      const value = row[col.prop]
      if (typeof value === 'string') {
        return `"${value.replace(/"/g, '""')}"` // 处理包含逗号、引号或换行的字符串
      }
      return String(value)
    }).join(',')
  }).join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `${currentDataInfo.value.title.replace(/[^a-zA-Z0-9]/g, '_')}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('图表数据已导出为CSV')
}

// 下载图表
const downloadChart = (segment, index) => {
  const chart = chartInstances.value.get(index)
  if (!chart) {
    ElMessage.error('图表实例未找到')
    return
  }

  try {
    const url = chart.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })

    const link = document.createElement('a')
    link.download = `chart-${Date.now()}.png`
    link.href = url
    link.click()

    ElMessage.success('图表下载成功')
  } catch (error) {
    console.error('图表下载失败:', error)
    ElMessage.error('图表下载失败')
  }
}

// 图表点击处理
const handleChartClick = (segment, event) => {
  console.log('图表容器点击:', segment, event)
}

// 显示图表配置
const showChartConfig = (segment) => {
  currentConfigText.value = JSON.stringify(segment.config, null, 2)
  showConfigDialog.value = true
}

// 复制配置
const copyConfig = async () => {
  try {
    await navigator.clipboard.writeText(currentConfigText.value)
    ElMessage.success('配置已复制到剪贴板')
    showConfigDialog.value = false
  } catch {
    ElMessage.error('复制失败')
  }
}

// 复制代码
const copyCode = async (segment) => {
  try {
    await navigator.clipboard.writeText(segment.originalContent || segment.content)
    ElMessage.success('代码已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败')
  }
}

// 🎯 新增：格式化数字显示
const formatNumber = (value) => {
  if (typeof value !== 'number') return value

  // 判断是否为整数
  if (Number.isInteger(value)) {
    return value.toLocaleString()
  }

  // 小数保留2位
  return value.toLocaleString(undefined, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  })
}

// 监听内容变化
watch(() => props.content, (newContent) => {
  parsedSegments.value = parseContent(newContent)

  // 延迟渲染图表
  nextTick(() => {
    parsedSegments.value.forEach((segment, index) => {
      if (segment.type === 'echarts' && segment.config) {
        renderChart(segment, index)
      }
    })
  })
}, { immediate: true })

// 监听暗色模式变化
watch(() => props.isDarkMode, () => {
  // 重新渲染所有图表以应用新主题
  nextTick(() => {
    parsedSegments.value.forEach((segment, index) => {
      if (segment.type === 'echarts' && segment.config) {
        renderChart(segment, index)
      }
    })
  })
})

// 组件销毁时清理图表实例
onBeforeUnmount(() => {
  chartInstances.value.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
  chartInstances.value.clear()
  chartRefs.value.clear()
})

// 初始化
onMounted(() => {
  parsedSegments.value = parseContent(props.content)
})
</script>

<style scoped>
.advanced-markdown-renderer {
  line-height: 1.6;
  color: var(--el-text-color-primary);
}

.content-segment {
  margin-bottom: 16px;
}

.content-segment:last-child {
  margin-bottom: 0;
}

/* 文本内容样式 */
.text-content {
  word-wrap: break-word;
}

.text-content :deep(h1),
.text-content :deep(h2),
.text-content :deep(h3),
.text-content :deep(h4),
.text-content :deep(h5),
.text-content :deep(h6) {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.text-content :deep(h1) { font-size: 24px; }
.text-content :deep(h2) { font-size: 20px; }
.text-content :deep(h3) { font-size: 18px; }
.text-content :deep(h4) { font-size: 16px; }
.text-content :deep(h5) { font-size: 14px; }
.text-content :deep(h6) { font-size: 12px; }

.text-content :deep(p) {
  margin: 8px 0;
  line-height: 1.7;
}

.text-content :deep(ul),
.text-content :deep(ol) {
  margin: 8px 0;
  padding-left: 24px;
}

.text-content :deep(li) {
  margin: 4px 0;
}

.text-content :deep(blockquote) {
  margin: 16px 0;
  padding: 8px 16px;
  border-left: 4px solid var(--el-color-primary);
  background-color: var(--el-fill-color-lighter);
  color: var(--el-text-color-regular);
  font-style: italic;
}

.text-content :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
}

.text-content :deep(th),
.text-content :deep(td) {
  border: 1px solid var(--el-border-color);
  padding: 8px 12px;
  text-align: left;
}

.text-content :deep(th) {
  background-color: var(--el-fill-color-light);
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.text-content :deep(code) {
  background-color: var(--el-fill-color-light);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', 'Monaco', 'Menlo', monospace;
  font-size: 90%;
  color: var(--el-color-primary);
}

.text-content :deep(pre) {
  background-color: var(--el-fill-color-lighter);
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 16px 0;
}

.text-content :deep(pre code) {
  background: none;
  padding: 0;
  color: inherit;
}

/* 图表容器样式 */
.chart-container {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  overflow: hidden;
  background: var(--el-bg-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color);
}

.chart-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.chart-actions {
  display: flex;
  gap: 8px;
}

.chart-element {
  width: 100%;
  height: 400px;
  padding: 16px;
  cursor: default;
}

.chart-error {
  padding: 16px;
}

.error-details p {
  margin: 0 0 8px 0;
}

/* 增强代码块样式 */
.enhanced-code-container {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  overflow: hidden;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color);
  font-size: 12px;
}

.code-language {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--el-text-color-secondary);
  text-transform: uppercase;
}

.code-actions {
  display: flex;
  gap: 8px;
}

.code-content {
  overflow-x: auto;
}

.code-content :deep(pre) {
  margin: 0;
  padding: 16px;
  background: transparent !important;
  border-radius: 0;
}

.code-content :deep(code) {
  font-family: 'Courier New', 'Monaco', 'Menlo', monospace;
  font-size: 13px;
  line-height: 1.4;
}

/* 配置查看器样式 */
.config-viewer :deep(.el-textarea__inner) {
  font-family: 'Courier New', 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  line-height: 1.4;
}

/* 数据查看对话框样式 */
.data-dialog :deep(.el-dialog__header) {
  background-color: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color);
}

.data-dialog :deep(.el-dialog__body) {
  padding: 16px;
}

.data-dialog :deep(.el-dialog__footer) {
  background-color: var(--el-fill-color-lighter);
  border-top: 1px solid var(--el-border-color);
  padding: 12px 16px;
}

.data-viewer-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color);
}

.data-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.data-title {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.data-count {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.data-actions {
  display: flex;
  gap: 8px;
}

.data-table-container {
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.data-table :deep(.el-table__header-wrapper) {
  background-color: var(--el-fill-color-light);
}

.data-table :deep(.el-table__inner-wrapper) {
  border-top: 1px solid var(--el-border-color);
}

.data-table :deep(.el-table__cell) {
  padding: 8px 12px;
}

.data-table :deep(.el-table__cell .number-cell) {
  color: var(--el-color-primary);
}

/* 暗色模式 */
.dark-mode {
  color: var(--el-text-color-primary);
}

.dark-mode .chart-container,
.dark-mode .enhanced-code-container {
  border-color: var(--el-border-color-light);
  background: var(--el-bg-color-page);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.dark-mode .chart-header,
.dark-mode .code-header {
  background: var(--el-fill-color-dark);
  border-color: var(--el-border-color-light);
}

.dark-mode .data-dialog :deep(.el-dialog__header) {
  background-color: var(--el-fill-color-dark);
  border-bottom: 1px solid var(--el-border-color-light);
}

.dark-mode .data-dialog :deep(.el-dialog__body) {
  background-color: var(--el-bg-color-page);
}

.dark-mode .data-dialog :deep(.el-dialog__footer) {
  background-color: var(--el-fill-color-dark);
  border-top: 1px solid var(--el-border-color-light);
}

.dark-mode .data-table-container {
  border-color: var(--el-border-color-light);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.dark-mode .data-table :deep(.el-table__header-wrapper) {
  background-color: var(--el-fill-color-dark);
}

.dark-mode .data-table :deep(.el-table__inner-wrapper) {
  border-top: 1px solid var(--el-border-color-light);
}

.dark-mode .data-table :deep(.el-table__cell) {
  color: var(--el-text-color-regular);
}

.dark-mode .data-table :deep(.el-table__cell .number-cell) {
  color: var(--el-color-primary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-element {
    height: 300px;
    padding: 8px;
  }

  .chart-header,
  .code-header {
    padding: 8px 12px;
  }

  .chart-actions,
  .code-actions {
    gap: 4px;
  }

  .chart-title span,
  .code-language span {
    display: none;
  }
}

/* 动画效果 */
.content-segment {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
.chart-element::-webkit-scrollbar,
.code-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.chart-element::-webkit-scrollbar-track,
.code-content::-webkit-scrollbar-track {
  background: var(--el-fill-color-lighter);
}

.chart-element::-webkit-scrollbar-thumb,
.code-content::-webkit-scrollbar-thumb {
  background: var(--el-border-color-darker);
  border-radius: 3px;
}

.chart-element::-webkit-scrollbar-thumb:hover,
.code-content::-webkit-scrollbar-thumb:hover {
  background: var(--el-text-color-disabled);
}
</style>
